import type {
  CellContext,
  ColumnDef,
  ColumnDefTemplate,
  StringOrTemplateHeader,
  TableOptions,
} from '@tanstack/react-table';
import type { Props as DefaultStatusProps } from '../DefaultStatus';
import type { PaginationProps } from '../Pagination';
import type { FilterListItem as FilterItem } from '../TableFilter/type';
import type { SettingCheckBoxInfo } from './components/DisplayTable';
import type { ValidateResult } from './utils/json-schema/interface';

import { TableContext } from './context/table';
export type { FilterListItem as FilterItem } from '../TableFilter/type';

export type FilterList = false | FilterItem[];
export type Size = 'large' | 'middle' | 'small';
export type SortType = 'single' | 'multiple';
export type Align = 'left' | 'center' | 'right';
export type DragType = 'row' | 'column';
export type DragSortType = true | DragType | DragType[];

export type ActionType = 'add' | 'remove' | 'copy';
export type ActionTypes = ActionType | ActionType[];
export type RowKey = string;
export type FilterCopyKey = string | string[];
export type TableSelectType = 'checkbox' | 'radio';
export type EditType =
  | 'string'
  | 'input'
  | 'number'
  | 'select'
  | 'switch'
  | 'radio'
  | 'checkbox'
  | 'date'
  | 'modal';
export type TablePagination = false | PaginationProps;

export type ColumnPinning = { left: string[]; right: string[] };
export type ColumnPinningInfo = {
  left: { [key in string]: number };
  right: { [key in string]: number };
};
export type ColumnFormulaInfo<T extends AnyObject> = {
  [columnId in keyof T]?: string;
}; // 列计算公式
export type ColumnDataKeyInfo<T extends AnyObject> = {
  [columnId in keyof T]?: keyof T;
}; // 显示dataKey的配置

export interface Rule {
  type?: 'string' | 'number' | 'boolean' | 'array';
  message?: string;
  /** String 类型时为字符串长度；number 类型时为确定数字； array 类型时为数组长度 */
  len?: number;
  /** 必须设置 type：string 类型为字符串最大长度；number 类型时为最大值；array 类型时为数组最大长度 */
  max?: number;
  /** 必须设置 type：string 类型为字符串最小长度；number 类型时为最小值；array 类型时为数组最小长度 */
  min?: number;
  pattern?: string;
  required?: boolean;
}
export type TableContextRef<T extends AnyObject> = {
  getTableContext: () => TableContext<T>;
  validateTable?: () => Errors<T>;
  onResizeTable?: () => void;
};
export type SelectTableRef<T extends AnyObject> = {
  getSelectedRows: () => T[];
};
export type ColumnSizes<T extends AnyObject> = { [key in keyof T]?: number };
export type Rules<T extends AnyObject> = { [key in keyof T]?: Rule[] };
export type ValidateError<T extends AnyObject> = {
  [key in keyof T]?: ValidateResult[];
};
export type Errors<T extends AnyObject> = ValidateError<T>[];
export type Sort = 'asce' | 'desc' | 'none';
export type Sorter = {
  compare?: (a: AnyObject, b: AnyObject) => number;
  multiple?: number;
};
// 当前操作的表格信息
export type CurOperateInfo<T extends AnyObject> = {
  rowIndex: number;
  columnId: string;
  data: T; // 保存的行数据
  meta: ColumnMeta<T>;
  curValue: any; // 当前列该行的显示值
};
// 表格弹窗参数
export type TableModalParams<T extends AnyObject> = { [key in keyof T]?: any };

export interface AnyObject {
  [key: string]: any;
}
export interface BaseColumnMeta {
  editType?: EditType;
  editProps?: any;
  dataKey?: string; // 显示的key 值
  align?: Align;
  className?: string;
  fixed?: boolean | 'left' | 'right';
  dataType?: EditType; // 显示的数据类型用于生成默认值，editType 优先级大于 dataType
  formula?: string; // 可根据其他列值计算该列值的公式， {columnId1}+{columnId2}
  rule?: Rule[];
  ellipsis?: boolean;
  sorter?: boolean | Sorter;
}
export interface GetModalDataResponse<T extends AnyObject> {
  page: number;
  size: number;
  total: number;
  list: T[];
}
export interface ColumnMeta<T extends AnyObject> extends BaseColumnMeta {
  columns?: Column<T>[];
  parent?: Column<T>;
  // render?: (data: T, i: number) => any;
  editPropsFn?: (data: T, i: number) => AnyObject;
  getModalData?: (
    page: number,
    size: number,
    params?: AnyObject,
  ) => Promise<GetModalDataResponse<T>>; // 弹窗请求方法
}
export interface TableMeta {
  updateCellData: (
    rowIndex: number,
    columnId: number | string,
    value: any,
  ) => void;
  updateColumnVisivleData: (id: string, visible: boolean) => void;
  updateSummaryData: (id: string, isSummary: boolean) => void;
}

export type TableOnRow<T extends AnyObject> = (
  data?: T,
  index?: number,
) => {
  onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  onDoubleClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  onMouseEnter?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  onMouseLeave?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
};
export type TableOnCellEventData = {
  id: string;
  params?: AnyObject;
};
export type TableOnCellEvent = {
  onClick?: (
    data: TableOnCellEventData,
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
  ) => void;
  onDoubleClick?: (
    data: TableOnCellEventData,
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
  ) => void;
  onMouseEnter?: (
    data: TableOnCellEventData,
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
  ) => void;
  onMouseLeave?: (
    data: TableOnCellEventData,
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
  ) => void;
};
export type TableOnCell<T extends AnyObject> = (
  data?: T,
  index?: number,
) => TableOnCellEvent;
export type TableModal<T extends AnyObject> = {
  isUsePop?: boolean;
  isCanRepeatSelection?: boolean;
  getContainer?: string | HTMLElement | (() => HTMLElement) | false;
  title?: string;
  rowKey?: RowKey;
  size?: Size;
  selectType?: TableSelectType;
  filterList?: FilterItem[];
  modalDataDetailKey?: string; // 插入源表格数据，详情的key，默认 'modalDataDetail
  getModalDataDetail?: (params?: AnyObject) => Promise<AnyObject>; // 选中数据详情请求
  onConfirm?: (selectedRows: T[]) => void;
  onCancel?: () => void;
};
export type Column<T extends AnyObject, V = unknown> = ColumnDef<T, V> & {
  id?: string;
  header?: StringOrTemplateHeader<T, V>;
  cell?: ColumnDefTemplate<CellContext<T, V>>;
  meta?: ColumnMeta<T>;
};
// 选择功能配置
export type RowSelection<T extends AnyObject> = {
  isCanRepeatSelection?: boolean; // 弹窗选择数据是否可重复
  // fixed?: boolean;
  columnWidth?: number; // 默认60px
  type: TableSelectType; // 默认 checkbox
  selectedRows?: T[];
  selectCellProps?: (
    data: T,
    index: number,
  ) => {
    disabled?: boolean;
  }; // 配置选择表格的多选单选框的props
  onChange?: (selectedRows: T[]) => void;
};
export interface DefaultTableProps<T extends AnyObject, Context = any> {
  id?: string;
  /** 表格大小 */
  size?: Size;
  /** 前缀类名 */
  prefixCls?: string;
  /** 数据key唯一标识 */
  rowKey?: RowKey;
  /** 展示外边框和列边框 */
  bordered?: boolean;
  /** 调整列宽 */
  isCanResizeColumn?: boolean;
  /** 显示合计 */
  isShowSummary?: boolean;
  /** 固定表格为最高高度 */
  isFixedHeight?: boolean;
  columns?: Column<T>[];
  dataSource?: T[];
  pagination?: TablePagination;
  context?: React.Context<Context>;
  tableStyle?: React.CSSProperties;
  tableBoxStyle?: React.CSSProperties;
  defaultStatus?: DefaultStatusProps;
  tableOptions?: Partial<TableOptions<T>>; // 表格api tableOption 配置
  onChangeDataSource?: (dataSource: T[]) => void;
  onChangePagination?: (
    page: number,
    pageSize: number,
    params?: AnyObject,
  ) => void;
  onRow?: TableOnRow<T>;
  onCell?: TableOnCell<T>;
}
// 基础表格type
export interface BaseTableProps<T extends AnyObject, Context = any>
  extends DefaultTableProps<T, Context> {
  columnPinning: ColumnPinning;
  dragTypes: DragType[];
  columnSummary: SettingCheckBoxInfo;
  columnVisibility: SettingCheckBoxInfo;
}
export interface DisplayTableProps<T extends AnyObject, Context = any>
  extends DefaultTableProps<T, Context> {
  isShowIndex?: boolean; // 显示时请不要使用 "index" 作为 columns key
  isCanSetting?: boolean; // 列设置(显示，合计)
  dragSrotType?: DragSortType; // true时同时支持行列拖拽
  rowSelection?: RowSelection<T>;
}
export interface EditableTableProps<T extends AnyObject>
  extends DisplayTableProps<T> {
  isSaveInRealTime?: boolean; // 编辑状态下是否实时保存
  defaultRows?: number;
  action?: ActionTypes;
  filterCopyKey?: FilterCopyKey;
  modal?: TableModal<T>;
}
export interface StongTableProps<T extends AnyObject>
  extends EditableTableProps<T> {
  isCanEdit?: boolean;
}
